<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE音频流测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .controls {
            margin: 20px 0;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
            font-size: 16px;
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
        }
        .connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        .chunk-info {
            margin: 10px 0;
            padding: 10px;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <h1>SSE音频流测试</h1>
    
    <div class="controls">
        <button id="startBtn">开始播放</button>
        <button id="stopBtn" disabled>停止播放</button>
    </div>
    
    <div id="status" class="status" style="display: none;"></div>
    
    <div class="chunk-info">
        <h3>音频块信息</h3>
        <div id="chunkInfo">等待接收数据...</div>
        <div id="currChunk"></div>
    </div>
    
    <div class="chunk-info">
        <h3>原始数据预览</h3>
        <div id="rawData" style="font-family: monospace; white-space: pre-wrap; max-height: 200px; overflow-y: auto;"></div>
    </div>

    <script>
        class SSEAudioTest {
            constructor() {
                this.eventSource = null;
                this.receivedChunkCount = 0;
                this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
                this.isPlaying = false;
                
                this.init();
            }
            
            init() {
                document.getElementById('startBtn').addEventListener('click', () => this.startPlayback());
                document.getElementById('stopBtn').addEventListener('click', () => this.stopPlayback());
            }
            
            startPlayback() {
                // 禁用开始按钮，启用停止按钮
                document.getElementById('startBtn').disabled = true;
                document.getElementById('stopBtn').disabled = false;
                
                // 更新状态
                this.updateStatus('正在连接到音频流...', 'info');
                
                // 创建SSE连接
                this.eventSource = new EventSource('sse-audio.php');
                
                // 监听消息事件
                this.eventSource.onmessage = (event) => {
                    this.handleMessage(event.data);
                };
                
                // 监听自定义事件
                this.eventSource.addEventListener('end', (event) => {
                    this.handleEnd(event.data);
                });
                
                // 监听错误事件
                this.eventSource.onerror = (event) => {
                    this.handleError(event);
                };
            }
            
            stopPlayback() {
                if (this.eventSource) {
                    this.eventSource.close();
                    this.eventSource = null;
                }
                
                // 启用开始按钮，禁用停止按钮
                document.getElementById('startBtn').disabled = false;
                document.getElementById('stopBtn').disabled = true;
                
                // 更新状态
                this.updateStatus('连接已关闭', 'info');
            }
            
            handleMessage(data) {
                try {
                    const audioData = JSON.parse(data);
                    this.receivedChunkCount++;
                    
                    // 显示原始数据预览
                    const preview = JSON.stringify(audioData, null, 2).substring(0, 200) + '...';
                    document.getElementById('rawData').textContent = preview;
                    
                    // 更新状态
                    this.updateStatus('正在接收音频数据...', 'connected');
                    
                    // 更新音频块信息
                    document.getElementById('chunkInfo').textContent = 
                        `已接收 ${this.receivedChunkCount} 个音频块`;
                    
                    // 处理不同类型的数据
                    if (audioData.frameType === "1") {
                        // 音频流数据
                        document.getElementById('currChunk').textContent = 
                            `当前处理: 音频流数据块 (frameType: 1)`;
                        console.log('接收到音频流数据:', audioData.audioData ? audioData.audioData.substring(0, 50) + '...' : '无音频数据');
                    } else if (audioData.frameType === "0") {
                        // 结束帧
                        document.getElementById('currChunk').textContent = 
                            `当前处理: 结束帧 (frameType: 0)`;
                        console.log('接收到结束帧');
                    } else if (audioData.data && audioData.workId) {
                        // 初始数据帧
                        document.getElementById('currChunk').textContent = 
                            `当前处理: 初始数据帧 (workId: ${audioData.workId})`;
                        console.log('接收到初始数据帧:', audioData);
                    } else {
                        // 其他数据
                        document.getElementById('currChunk').textContent = 
                            `当前处理: 其他数据`;
                        console.log('接收到其他数据:', audioData);
                    }
                } catch (e) {
                    console.error('解析数据错误:', e);
                    console.log('原始数据:', data);
                }
            }
            
            handleEnd(data) {
                try {
                    const endData = JSON.parse(data);
                    this.updateStatus('音频流结束', 'connected');
                    document.getElementById('currChunk').textContent = 
                        `流结束: ${endData.msg || '完成'}`;
                    console.log('流结束:', endData);
                } catch (e) {
                    console.error('解析结束数据错误:', e);
                }
                
                // 自动停止播放
                this.stopPlayback();
            }
            
            handleError(event) {
                this.updateStatus('连接错误', 'error');
                console.error('SSE连接错误:', event);
                
                // 自动停止播放
                this.stopPlayback();
            }
            
            updateStatus(message, className) {
                const statusEl = document.getElementById('status');
                statusEl.textContent = message;
                statusEl.className = 'status ' + className;
                statusEl.style.display = 'block';
            }
        }
        
        // 初始化测试
        document.addEventListener('DOMContentLoaded', () => {
            new SSEAudioTest();
        });
    </script>
</body>
</html>